const express = require("express");
const path = require("path");
const http = require("http");
const WebSocket = require("./webSocket");  // 引入 WebSocket 服务器文件
const app = express();
const server = http.createServer(app);
const formidable = require("express-formidable");
const bodyParser = require("body-parser");

const { middleware } = require("./middleware");
app.use(bodyParser.json());

//处理跨域
const cors = require("cors");
app.use(cors());

const common = require("./routes/common");
const user = require("./routes/user");
const shop_user = require("./routes/shop_user");
const banner = require("./routes/banner");
const menu = require("./routes/menu");
const student = require("./routes/student");
const wxupload = require("./routes/wxupload");
app.use(function (req, res, next) {
  res.success = function (msg = "成功", data = [], code = 200) {
    res.send({
      code,
      data,
      msg,
    });
  };
  res.err = function (msg = "失败", data = [], code = 500) {
    res.send({
      code,
      data,
      msg,
    });
  };
  next();
});
//鉴权中间件
app.use(middleware);
app.use("/common", common);
app.use("/", user);
app.use("/banner", banner);
app.use("/shop_user", shop_user);
app.use("/menu", menu);
app.use("/admin", student);
app.use("/admin", wxupload);
// 将静态资源目录设置为项目根目录下的 uploads 目录
app.use(express.static(path.join(__dirname, "uploads")));

app.use((err, req, res, next) => {
  console.log("err: ", err);
  //判断是否由 Token 解析失败导致的
  if (err.name == "UnauthorizedError") {
    return res.send({
      status: 401,
      message: "无效的Token",
    });
  }
  res.send({
    status: 500,
    message: "未知的错误",
  });
});

// 启动 WebSocket 服务器和 Express 服务器
WebSocket.startWebSocket(server);

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Express 和 WebSocket 服务器正在监听端口 ${PORT}`);
});
